﻿console.log("我是pinduoduo.js");

var returnNum = {};
returnNum.success = 0;//成功发货
returnNum.notDelivered = 0;
returnNum.noNote = 0;

var errorNotes = [];

var curGood = 0;
var totalGood = 0;

var unsoldGoodCount = 0;
/**
 * 接收消息
 */
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

    //读取用户名，手机号，地址
    if (request.type == "background_getUserInfo") {
        //这里是使用快捷键的时候,直接收到的background.js的请求时的操作
        //1.读取相关信息
        var userInfo = document.getElementsByClassName("o-d-b-i-c-people")[0];

        var nameSpan = userInfo.getElementsByTagName("span")[1];
        var name = nameSpan.innerText;

        var phoneSpan = userInfo.getElementsByTagName("span")[2];
        var phone = phoneSpan.innerText;

        var addressSpan = document.getElementsByClassName("o-d-b-i-c-address")[0].getElementsByTagName("span")[1];
        var address = addressSpan.innerText;

        var goodName = document.getElementsByClassName("pdd-dui-table")[0].getElementsByTagName("td")[1].innerText;
        //2.把相关的信息返回给background.js
        sendResponse({
            type: "pinduoduo_getUserInfo",
            name: name,
            phone: phone,
            address: address,
            goodName: goodName
        });

        copyTextToClipboard(address);
        alert(address);
        copyTextToClipboard(name);
        alert(name);
        copyTextToClipboard(phone);
        alert(phone);

        console.log(name);
        console.log(phone);
        console.log(address);
        console.log(goodName);
    } else if (request.type == "background_oneKeyDeliver") {
        sendResponse({farewell: "success"});
        oneKeyDeliver();
    } else if (request.type == "background_doDeliver") {
        sendResponse({farewell: "success"});
        getWaybillInfo(request.order, request.orderSn, request.userid);
    } else if (request.type == "background_doOneKeyDeliver") {
        sendResponse({farewell: "success"});
        doOneKeyDeliver();
    } else if (request.type == "background_noBuyerTrade") {
        sendResponse({farewell: "success"});
        noBuyerTrade();
    } else if (request.type == "background_giveUserId") {
        sendResponse({farewell: "success"});
        //已经拿到了userid 获取快递信息然后发货了
        getWaybillInfo(request.order, request.orderSn, request.userid);
    } else if (request.type == "background_getPhone") {
        sendResponse({farewell: "success"});
        //首先获取用户手机号
        getPhone();
    } else if (request.type == "background_unsoldGoods") {
        sendResponse({farewell: "success"});
        //首先获取用户手机号
        unsoldGoods();
    }
});

function copyTextToClipboard(text) {
    var copyFrom = document.createElement("textarea");
    copyFrom.textContent = text;
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(copyFrom);
    copyFrom.select();
    document.execCommand('copy');
    body.removeChild(copyFrom);
}

function unsoldGoods() {
    unsoldGoodCount = 0;
    setTimeout(function () {
        alert("成功下架了" + unsoldGoodCount + "件商品");
    }, 1000);

    var table = document.getElementsByClassName("pdd-dui-table")[1];
    var tbody = table.getElementsByTagName("tbody")[0];
    var trs = tbody.getElementsByTagName("tr");

    for (var i = 0; i < trs.length; i++) {
        var goodId = trs[i].getElementsByTagName('p')[0].innerText;

        var url = "https://mms.pinduoduo.com/glide/v2/mms/edit/switch/offSale";
        var params = {};
        params["goods_id"] = goodId;

        $.ajax(url, {
            type: "POST",
            async: true,
            data: JSON.stringify(params),
            crossDomain: true,
            contentType: "application/json; charset=utf-8",
            dataType: "json",//"xml", "html", "script", "json", "jsonp", "text".
            // xhrFields: {  withCredentials: true  },
            //成功返回之后调用的函数
            success: function (data, status) {
                console.log(data);
                if (data.success == true) {
                    //成功的拿到了数据
                    //说明成功下架
                    unsoldGoodCount++;
                }
            }
        });
    }
}

function getPhone() {
    var table = document.getElementsByClassName("absolute-show")[0];
    table.getElementsByTagName("a")[0].click();
}

function searchNote(order_sn) {
    console.log("searchNote");

    var url = "https://mms.pinduoduo.com/mars/shop/getNoteList";

    var params = {};
    params["orderSn"] = order_sn;

    $.ajax(url, {
        type: "POST",
        async: true,
        data: JSON.stringify(params),
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",//"xml", "html", "script", "json", "jsonp", "text".
        // xhrFields: {  withCredentials: true  },
        //成功返回之后调用的函数
        success: function (data, status) {
            console.log(data);
            if (data.success == true) {
                //成功的拿到了数据
                //读取出来对应的备注
                var result = data.result;
                if (result.length > 0) {//说明有备注
                    // var note = data.result[0].note;
                    // var orderSn = data.result[0].orderSn;
                    var alertText = "从上到下...";

                    for (var i = 0; i < result.length; i++) {
                        var temp = i + 1;
                        alertText += ("第" + temp + "条备注为：" + result[i].note + "...");
                    }

                    prompt("", alertText);
                } else {//说明没有备注
                    alert("该订单没有备注");
                }
            }
        }
    });
}

/**
 * 一键发货 调用流程 oneKeyDeliver->getNode->getWaybillInfo->doDeliver
 */
function oneKeyDeliver() {
    //归零所有记录字段
    curGood = 0;
    totalGood = 0;
    returnNum.success = 0;
    returnNum.notDelivered = 0;
    returnNum.noNote = 0;
    returnNum.noteError = 0;

    errorNotes = [];

    chrome.runtime.sendMessage({
        type: "pinduoduo_hasBuyerTrade"
    }, function (response) {
    });
}

function noBuyerTrade() {
    alert("没有buyertrade.taobao.com页面\n请依次打开淘宝->我的淘宝->已买到的宝贝");
}

function doOneKeyDeliver() {
    //一切正常执行发货
    var orders = document.getElementsByClassName("o-o-t-l-c-l-table-title");
    totalGood = orders.length;

    var baseUrl = "https://i.taobao.com/my_taobao.htm";
    //读取出来网页
    for (curGood = totalGood - 1; curGood >= 0; curGood--) {
        var tempText = orders[curGood].getElementsByTagName("li")[0].innerText;
        var orderSn = tempText.substring(tempText.indexOf("：") + 1);

        getNote(orderSn);
    }

    var timeOut = 160 * totalGood;
    if (timeOut < 2000) {
        timeOut = 2000;
    }
    setTimeout(function () {
        alert("共有商品" + totalGood + "件\n" +
            "成功发货 " + returnNum.success + " 件\n" +
            "没有备注的商品" + returnNum.noNote + "件\n" +
            "备注有错" + returnNum.noteError + "件   " + errorNotes + "\n" +
            "淘宝还未发货的商品" + returnNum.notDelivered + "件\n\n" +
            "未发货可能因为\n" +
            "1. 未打开对应的淘宝所有订单页面\n" +
            "2. 订单号的备注不在备注中的第一个 (从上到下数)\n" +
            "3. 还未购买,所以没有备注（正常情况");
    }, timeOut);
}

/**
 * 为了发货,获取到备注中的 淘宝订单号
 * @param order_sn
 */
function getNote(order_sn) {
    //2018-5-2 加入免拼卡，致使getNote拿不到正确的order_sn(多了免拼两个字)，出现弹窗警告，特此修复
    var orderSnLength = order_sn.length;
    var temp = order_sn.substr(orderSnLength - 2, 2);
    if (temp == "免拼") {
        order_sn = order_sn.substr(0, orderSnLength - 2);
    }
    console.log("getNode\t拼多多订单" + order_sn);
    var url = "https://mms.pinduoduo.com/mars/shop/getNoteList";

    var params = {};
    params["orderSn"] = order_sn;

    $.ajax(url, {
        type: "POST",
        async: true,
        data: JSON.stringify(params),
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",//"xml", "html", "script", "json", "jsonp", "text".
        // xhrFields: {  withCredentials: true  },
        //成功返回之后调用的函数
        success: function (data, status) {
            if (data.success == true) {
                //成功的拿到了数据
                //读取出来对应的备注
                if (data.result.length > 0) {//说明有备注
                    var note = data.result[0].note;
                    var orderSn = data.result[0].orderSn;

                    getUserId(note, orderSn);
                } else {//说明没有备注
                    returnNum.noNote++;
                }
            } else {
                alert("参数不正确,拼多多或服务器有问题");
            }
        }
    });
}

function getUserId(order, orderSn) {
    chrome.runtime.sendMessage({
        type: "pinduoduo_getUserId",
        order: order,
        orderSn: orderSn
    }, function (response) {
    });
}

/**
 * 淘宝的接口，拿到了快递号 种类
 * @param order 淘宝订单号
 * @param orderSn 拼多多订单号
 * @param userid 淘宝id
 */
function getWaybillInfo(order, orderSn, userid) {
    console.log("getWayBillInfo\t淘宝订单" + order + "\t" + orderSn + "\t" + userid);
    var url = "https://detail.i56.taobao.com/trace/trace_detail.htm?" +
        "tId=" + order +
        "&userId=" + userid;

    console.log(url);
    if (userid != "") {
        $.get(url, function (data, status) {
            //解析返回数据,
            //登录失败,服务器错误,提示用户原因
            if (status != "success") {
                promptUser("登录失败￣□￣｜｜\n请稍后再试");
            } else {
                var htmlString = data.valueOf();
                if (htmlString.indexOf("您的快件还未发货，请耐心等待") == -1) {//说明已经可以查到订单好了
                    var expressId = htmlString.substring(htmlString.indexOf("运单号码"), htmlString.indexOf("物流公司"));
                    expressId = expressId.split("\n")[2];
                    expressId = expressId.substring(expressId.search("[^\t]"), expressId.length);

                    var expressName = htmlString.substring(htmlString.indexOf("物流公司"), htmlString.indexOf("客服电话"));
                    expressName = expressName.split("\n")[3];
                    expressName = expressName.substring(expressName.search("[^\t]"), expressName.length);
                    expressName = expressName.substring(0, expressName.length - 1);

                    switch (expressName) {
                        case "圆通速递":
                            expressName = "圆通快递";
                            break;
                        case "EMS":
                            expressName = "邮政EMS";
                            break;
                        case "EMS经济快递":
                            expressName = "邮政EMS";
                            break;
                    }
                    //已经完成了 快递名字的转换，下一步尝试发货
                    getRefundId(expressName, expressId, orderSn);
                } else {
                    returnNum.notDelivered++;
                }
            }
        });
    } else {
        console.log("该备注有问题" + order + "\t" + orderSn);
        returnNum.noteError++;
        errorNotes.push(orderSn);
    }

}

function getRefundId(expressName, expressId, orderSn) {
    console.log("getRefundId\t淘宝订单" + expressName + "\t" + orderSn + "\t" + expressId);
    var url = "https://mms.pinduoduo.com/earth/api/refundAddress/list";

    $.ajax(url, {
        //提交数据的类型 POST GET
        type: "POST",
        async: true,
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        // xhrFields: {  withCredentials: true  },
        //成功返回之后调用的函数
        success: function (data, status) {
            data = data.result;
            //解析所有的 订单种类，找到我们需要的
            for (var i = 0; i < data.length; i++) {
                if (data[i].refundAddress == "具体请联系客服，谢谢您的理解") {
                    refundId = data[i].refundId;
                    break;
                }
            }
            console.log(refundId);
            doDeliver(expressName, expressId, orderSn, refundId);
        }
    });
}


/**
 * 通过拼多多的接口执行发货
 * @param shippingName
 * @param trackingNumber
 * @param orderSn
 */
function doDeliver(shippingName, trackingNumber, orderSn, refundId) {
    console.log("doDeliver\t快递种类" + shippingName + "\t快递单号" + trackingNumber + "\t" + orderSn);
    var url = "https://mms.pinduoduo.com/express_base/shipping_list/mms";
    $.ajax(url, {
        //提交数据的类型 POST GET
        type: "GET",
        async: true,
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        dataType: "json",//"xml", "html", "script", "json", "jsonp", "text".
        // xhrFields: {  withCredentials: true  },
        //成功返回之后调用的函数
        success: function (data, status) {
            data = data.result;
            //解析所有的 订单种类，找到我们需要的
            for (var i = 0; i < data.length; i++) {
                if (data[i].shipping_name == shippingName) {
                    shippingId = data[i].shipping_id;
                    break;
                }
            }

            //拿到了订单ID，可以发货了
            var params = {};

            var list = [];
            list.push({
                "orderSn": orderSn,
                "shippingId": shippingId,
                "shippingName": shippingName,
                "trackingNumber": trackingNumber,
                "returnAddressId": refundId
        }) ;
            params["orderShipRequestList"] = list;

            params["overWrite"] = 1;
            params["isSingleShipment"] = 1;
            params["functionType"] = 3;
            params["operateFrom"] = 'MMS';

            url = "https://mms.pinduoduo.com/express_base/shop/orders/shipping";


            $.ajax(url, {
                type: "POST",
                async: true,
                data: JSON.stringify(params),
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                dataType: "json",//"xml", "html", "script", "json", "jsonp", "text".
                // xhrFields: {  withCredentials: true  },
                //成功返回之后调用的函数
                success: function (data, status) {
                    console.log("doDeliver");
                    console.log(data);
                    if (data.success == true) {
                        console.log(orderSn + "发货成功");
                        returnNum.success++;
                    }
                }
            });

        }
    });
}
